<?php

namespace Mogod\Core\Model\Scheme\Repository;

require_once __DIR__ . '/ModelSchemeRepositoryAbstract.php';

/**
 * Стандартный репозиторий схем моделей
 *
 * @author morph, goorus
 */
class ModelSchemeRepositoryStandart extends ModelSchemeRepositoryAbstract
{
	/**
	 * Хранилище схем модели
	 *
	 * @var Mogod\Core\Model\Scheme\Storage\ModelSchemeStorageAbstract
	 */
	protected $storage;

	/**
	 * Получить из хранилища схему моделей
	 *
	 * @param string $modelName
	 */
	protected function fetchModelScheme($modelName)
	{
		if (!isset($this->modelSchemes[$modelName])) {
			$scheme = $this->storage->loadScheme($modelName) ?: false;
			$this->modelSchemes[$modelName] = $scheme;
		}
	}

	/**
	 * @inheritdoc
	 */
	public function getFieldProperty($modelName, $fieldName, $propertyName)
	{
		$scheme = $this->getModelScheme($modelName);
		if (
			!$scheme ||
			!isset($scheme[self::FIELDS]) ||
			!isset($scheme[self::FIELDS][$fieldName]) ||
			!isset($scheme[self::FIELDS][$fieldName][$propertyName]))
		{
			return;
		}
		return $scheme[self::FIELDS][$fieldName][$propertyName];
	}

	/**
	 * @inheritdoc
	 */
	public function getModelProperty($modelName, $propertyName)
	{
		$scheme = $this->getModelScheme($modelName);
		if (
			!$scheme ||
			!isset($scheme[self::MODEL]) ||
			!isset($scheme[self::MODEL][$propertyName])
		) {
			return;
		}
		return $scheme[self::MODEL][$propertyName];
	}

	/**
	 * @inheritdoc
	 */
	public function getModelScheme($modelName)
	{
		$this->fetchModelScheme($modelName);
		return parent::getModelScheme($modelName);
	}

	/**
	 * Получить хранилище
	 *
	 * @return Mogod\Core\Model\Scheme\Storage\ModelSchemeStorageAbstract
	 */
	public function getStorage()
	{
		return $this->storage;
	}

	/**
	 * @inheritdoc
	 */
	public function setModelScheme($modelName, $scheme)
	{
		if (
			!empty($this->modelSchemes[$modelName]) &&
			$this->modelSchemes[$modelName][self::MODEL] != $scheme
		) {
			$this->storage->saveScheme($modelName, $scheme);
		}
		parent::setModelScheme($modelName, $scheme);
	}

	/**
	 * Изменить хранилище
	 *
	 * @param Mogod\Core\Model\Scheme\Storage\ModelSchemeStorageAbstract $storage
	 */
	public function setStorage($storage)
	{
		$this->storage = $storage;
	}
}